/*
 * @Author: xiaosihan
 * @Date: 2024-07-29 12:22:45
 * @Last Modified by: xiaosihan
 * @Last Modified time: 2025-08-23 20:14:36
 */

import { UserData } from "@/types/type";
import database from "../database";
import ServiceBase from "./ServiceBase";
import express from 'express';

// 用户服务类
export default class UserService extends ServiceBase {

    constructor(req: express.Request = {} as express.Request, res: express.Response = {} as express.Response) {
        super(req, res);
    }

    // 用户登录
    write_user_login = async (params: Record<string, any>) => {
        // 参数校验
        this.verifyParams(['username', 'password']);

        const { username, password } = params;

        // 查询用户
        const user = await database.user.findOne({
            where: {
                username,
                password
            }
        });

        if (!user) {
            throw new Error('用户名或密码错误');
        }

        return user.dataValues;
    };

    // 获取用户信息
    get_user = async (params: Record<string, any>) => {
        // 参数校验
        this.verifyParams(['id']);

        const { id } = params;

        // 权限验证：只能查看自己的信息
        const currentUser = params.user || {};
        if (currentUser.id !== id && currentUser.role !== 'admin') {
            throw new Error('无权限查看其他用户信息');
        }

        // 查询用户
        const user = await database.user.findByPk(id);

        if (!user) {
            throw new Error('用户不存在');
        }

        return user.dataValues;
    };

    // 添加用户
    write_user = async (params: Record<string, any>) => {
        // 参数校验
        this.verifyParams(['username', 'password']);

        const { username, password } = params;

        // 权限验证：需要管理员权限
        const currentUser = params.user || {};
        if (currentUser.role !== 'admin') {
            throw new Error('无权限添加用户');
        }

        // 检查用户是否已存在
        const existingUser = await database.user.findOne({
            where: { username }
        });

        if (existingUser) {
            throw new Error('用户名已存在');
        }

        // 创建用户
        const user = await database.user.create({
            username,
            password
        });

        return user.dataValues;
    };

    // 删除用户
    del_user = async (params: Record<string, any>) => {
        // 参数校验
        this.verifyParams(['id']);

        const { id } = params;

        // 权限验证：需要管理员权限
        const currentUser = params.user || {};
        if (currentUser.role !== 'admin') {
            throw new Error('无权限删除用户');
        }

        // 检查用户是否存在
        const user = await database.user.findByPk(id);
        if (!user) {
            throw new Error('用户不存在');
        }

        // 删除用户
        await database.user.destroy({
            where: {
                id
            }
        });

        return { success: true };
    };
}